package com.gcstorage.tvdev.ui.fragment;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.blankj.utilcode.util.LogUtils;
import com.gcstorage.tvdev.base.BaseAndroidJSInterface;
import com.gcstorage.tvdev.base.RxBaseFragment;
import com.gcstorage.tvdev.constants.AppConstant;
import com.gcstorage.tvdev.constants.LogCat;
import com.gcstorage.tvdev.databinding.FragmentWorkWebBinding;
import com.gcstorage.tvdev.util.H5AppManager;
import com.gcstorage.tvdev.view.CustomWebView;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * webview容器
 * created by Sanpark on 2020-11-11 16:45
 */
public class WebWorkFragment extends RxBaseFragment {
    FragmentWorkWebBinding binding;
    CustomWebView webView;
    public ValueCallback<Uri[]> mFilePathCallbacks;
    private boolean isLoadError = false;
    String appId;
    String url;
    Disposable disposable;

    @Override
    protected View getRootView(ViewGroup container) {
        binding = FragmentWorkWebBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    public static WebWorkFragment newInstance(String appId) {
        Bundle args = new Bundle();
        args.putString("appId", appId);
        WebWorkFragment fragment = new WebWorkFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static WebWorkFragment newInstanceUrl(String url) {
        Bundle args = new Bundle();
        args.putString("url", url);
        WebWorkFragment fragment = new WebWorkFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.d("LogCat onResume---");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            ///此处可以刷新数据
        }

    }

    public void setNewUrl(int index) {

        webView.loadUrl("javascript:switchTabIndex('" + index + "')");

    }

    @Override
    public void initView() {
        webView = binding.webView;
//        binding.btnReload.setOnClickListener(v -> {
//            if (H5AppManager.getInstance().isExistApp(appId)) {
//                webView.loadUrl(H5AppManager.getAppIdLocalUrl(appId));
//                binding.clReload.setVisibility(View.GONE);
//            } else {
//                H5AppManager.getInstance().downloadAppByAppId(appId);
//            }
//        });
        initWebSetting();
        // 获取到UserAgentString
        String userAgent = webView.getSettings().getUserAgentString();
        LogUtils.d(LogCat.LOG_COMMONON + " userAgent " + userAgent);
    }


    @Override
    public void initData() {
        appId = getArguments().getString("appId");
        url = getArguments().getString("url");
        LogUtils.d(LogCat.LOG_COMMONON + " url " + url);
        if (appId != null) {
            binding.clReload.setVisibility(H5AppManager.getInstance().isExistApp(appId) ? View.GONE : View.VISIBLE);
            if (H5AppManager.getInstance().isExistApp(appId)) {
                webView.loadUrl(H5AppManager.getAppIdLocalUrl(appId));
            }
            H5AppManager.getInstance().downloadAppByAppId(appId);
            disposable = Observable.interval(1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(bindToLifecycle())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (H5AppManager.getInstance().isExistApp(appId)) {
                                webView.loadUrl(H5AppManager.getAppIdLocalUrl(appId));
                                binding.clReload.setVisibility(View.GONE);
                            }
                        }
                    });
        }
        if (url != null) {
            webView.loadUrl(url);
//            webView.loadUrl("https://www.baidu.com/");
        }
//        binding.clReload.setVisibility(H5AppManager.getInstance().isExistApp(appId) ? View.GONE : View.VISIBLE);
//        if (H5AppManager.getInstance().isExistApp(appId)) {
//            webView.loadUrl(H5AppManager.getAppIdLocalUrl(appId));
//        }
//        H5AppManager.getInstance().downloadAppByAppId(appId);
    }

    @SuppressLint("JavascriptInterface")
    private void initWebSetting() {

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);  //设置与Js交互的权限
        settings.setDomStorageEnabled(true);//开启本地DOM存储


        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setLoadWithOverviewMode(true);

//        // 设置可以支持缩放
        settings.setSupportZoom(true);
//        // 设置出现缩放工具
        settings.setBuiltInZoomControls(true);
        // 为图片添加放大缩小功能
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setTextZoom(80);

//        webView.setInitialScale(50);

//        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        settings.setAppCacheEnabled(true);
        webView.clearCache(true);
        webView.clearHistory();
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webView.addJavascriptInterface(new BaseAndroidJSInterface(mActivity, webView, AppConstant.getApiAddress()), "android");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (disposable != null) {
                    disposable.dispose();
                }
                binding.lottieView.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                isLoadError = true;
                LogUtils.d(LogCat.LOG_COMMONON + " error " + error.getDescription());
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
    }



}
